package com.bilibili.liveremind.module.util;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bilibili.liveremind.module.common.WxCommon;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class WxUtil {

    public static String accessToken = "";
    public static long oldMill = 0;

    public static String getWxOpenId(String jsCode){
        System.out.println("jsCode------"+jsCode);
        //1.根据微信code获取openid
        //get请求接口:https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String wxOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,Object> wxOpenIdMap = new HashMap<>();
        wxOpenIdMap.put("appid", WxCommon.appId);//小程序 appId
        wxOpenIdMap.put("secret",WxCommon.appSecret);//小程序 appSecret
        wxOpenIdMap.put("js_code",jsCode);//登录时获取的 code，可通过wx.login获取
        wxOpenIdMap.put("grant_type","authorization_code");//授权类型，此处只需填写 authorization_code
        //HttpUtil.get(wxOpenIdUrl,wxOpenIdMap);
        String res = HttpRequest.get(wxOpenIdUrl).form(wxOpenIdMap).execute().body();

        JSONObject resJson = JSONUtil.parseObj(res);;
        String openId = resJson.getStr("openid");
        System.out.println("openId-----:"+openId);
        return openId;
    }

    public static String getWxAccessToken(){
        //获取当前时间毫秒数
        long newMill = DateUtil.date().getTime();
        if ("".equals(accessToken) || newMill>=oldMill){
            //获取微信token接口
            //get请求接口：https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
            String wxAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
            Map<String,Object> wxAccessTokenMap = new HashMap<>();
            wxAccessTokenMap.put("grant_type","client_credential");
            wxAccessTokenMap.put("appid", WxCommon.appId);
            wxAccessTokenMap.put("secret",WxCommon.appSecret);
            String res = HttpRequest.get(wxAccessTokenUrl).form(wxAccessTokenMap).execute().body();
            /**
             * {
             * "access_token":"ACCESS_TOKEN",
             * "expires_in":7200
             * }
             */
            JSONObject resJson = JSONUtil.parseObj(res);
            accessToken = resJson.getStr("access_token");
            int expiresIn = resJson.getInt("expires_in");
            oldMill = newMill + (expiresIn* 1000L);
        }
        System.out.println("accessToken-----"+accessToken);
        return accessToken;
    }

    public static void SendWxMessage(String openId, String anchorName, String roomId, String roomTitle, DateTime liveStartTime){
        //模板内容
        /**
         * 达人名称{{thing1.DATA}}
         * 直播间名称{{thing2.DATA}}
         * 开播时间{{time3.DATA}}
         * 备注{{thing4.DATA}}
         */
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> thing1Map = new HashMap<>();
        thing1Map.put("value", anchorName+"-"+roomId);
        dataMap.put("thing1", thing1Map);
        Map<String, Object> thing2Map = new HashMap<>();
        thing2Map.put("value", roomTitle);
        dataMap.put("thing2", thing2Map);
        Map<String, Object> time3Map = new HashMap<>();
        time3Map.put("value", DateUtil.format(liveStartTime, "yyyy-MM-dd HH:mm"));
        dataMap.put("time3", time3Map);
        Map<String, Object> thing4Map = new HashMap<>();
        thing4Map.put("value", "开播啦开播啦开播啦");
        dataMap.put("thing4", thing4Map);
        //获取微信token
        String wxAccessToken = WxUtil.getWxAccessToken();//接口调用凭证，该参数为 URL 参数，非 Body 参数。使用access_token或者authorizer_access_token
        //发送微信订阅消息
        //post请求接口：https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
        String wxSendMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + wxAccessToken;
        Map<String,Object> wxSendMessageMap = new HashMap<>();
        wxSendMessageMap.put("template_id",WxCommon.templateIdList.get(0));//所需下发的订阅模板id
        wxSendMessageMap.put("touser",openId);//接收者（用户）的 openid oXzj84kYZs3lMk9ZU6CAqXYRrumA
        wxSendMessageMap.put("data",dataMap);//模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }的object
        wxSendMessageMap.put("miniprogram_state","trial");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        wxSendMessageMap.put("lang","zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN
        //String body = HttpRequest.post(wxSendMessageUrl).form(wxSendMessageMap).execute().body();
        String wxSendMessageMapStr = JSONUtil.toJsonStr(wxSendMessageMap);
        String body = HttpUtil.post(wxSendMessageUrl, wxSendMessageMapStr);
        System.out.println(body);
    }

    /*public static void main(String[] args) {
        WxUtil.SendWxMessage();
    }*/

}
